<?php

namespace app\lucky\controller;

use \app\check\controller\Check;
use app\common\cachemodel\ZlUserVip;
use app\common\lib\SensorsData;
use app\common\model\LuckyPlanet;
use app\common\model\LuckyQuestionAnswer;
use \think\Cache;

/**
 * 女神幸运星🌟
 * Class Planet
 * @package app\lucky\controller
 */
class Planet extends Check
{
    protected $total_day_max = 17500;// 总抽奖次数限制 0 代表不限制
    protected $user_day_max = 3;// 用户每日可抽奖次数上线 0 表示不限制
    protected $must_win = 3500;// 多少人中必中 0表示完全随机
    protected $time_interval = 14400;// 抽奖时间间隔 /s     0 表示无间隔时间
    protected $time_limit_switch = false;// 是否开启时间段中奖 false表示此功能关闭  true 表示此功能开启
    protected $time_limit = [];//中奖时间段 若需要使用此功能则 $time_limit_switch 必须为true才生效
    protected $rand_max = 5000;// 随机数最大值 与中奖率有关

    public function _initialize()
    {
        parent::_initialize();

        $this->init();
    }

    /**
     * 幸运星初始化
     */
    public function init()
    {
        $luckyPlanetConfig = config('luckyplanet');
        $this->total_day_max = $luckyPlanetConfig['total_day_max'];
        $this->user_day_max = $luckyPlanetConfig['user_day_max'];
        $this->must_win = $luckyPlanetConfig['must_win'];
        $this->time_interval = $luckyPlanetConfig['time_interval'];
        $this->total_day_max = $luckyPlanetConfig['total_day_max'];
        $this->rand_max = $luckyPlanetConfig['rand_max'];
        if ($this->rand_max < 12) $this->rand_max = 19;
    }

    /**
     * 幸运星首页
     */
    public function index()
    {
        $uid = $this->user['id'];

        $LuckyPlanet = new LuckyPlanet();

        // 获取当前抽奖总次数
        $total_count = $LuckyPlanet->getCountToday();
        // 获取用户今日抽奖情况
        $user_today = $LuckyPlanet->getUserToday(['uid' => $uid]);

        $user_surplus_times = 3;

        // 今日总抽奖次数已用尽
        if ($this->total_day_max > 0 && $total_count >= $this->total_day_max) $user_surplus_times = 0;

        if ($this->user_day_max > 0 && $user_surplus_times > 0) $user_surplus_times = $this->user_day_max - count($user_today);

        $winners = $LuckyPlanet->getWinToday(['uid' => $uid]);

        $lasttime = $this->user_day_max ? (empty($user_today) ? 1 : $user_today[0]['create_time']) : 0;

        $data = [
            'list' => $winners,
            'times' => $user_surplus_times,
            'last_time' => $lasttime,
        ];

        return show(config('code.success'), '加载成功', $data);
    }

    /**
     * 我的幸运星
     */
    public function get_my_lucky()
    {
        $uid = $this->user['id'];

        $LuckyPlanet = new LuckyPlanet();

        $map = ['uid' => (int)$uid, 'page' => input('page/d', 1)];

        $data = $LuckyPlanet->getList($map);

        return show(config('code.success'), '加载成功', $data);
    }

    /**
     * 领取幸运星
     */
    public function get()
    {
        $uid = (int)$this->user['id'];

        $time = time();

        $date = date('Ymd', $time);

        $LuckyPlanet = new LuckyPlanet();
        // 获取当前抽奖总次数
        $total_count = $LuckyPlanet->getCountToday();
        // 今日总抽奖次数已用尽
        if ($this->total_day_max > 0 && $total_count >= $this->total_day_max)
        {
            return show(config('code.error'), '今日奖励已发完，请明日再来领取！');
        }
        // 获取用户今日抽奖情况
        $user_today = $LuckyPlanet->getUserToday(['uid' => $uid]);

        $user_today_count = count($user_today);
        // 计算用户剩余抽奖次数
        $user_surplus_times = 3;
        if ($this->user_day_max > 0)
        {
            if ($user_today_count >= $this->user_day_max)
            {
                return show(config('code.error'), '今日已领取' . $user_today_count . '次，请明日再来领取！');
            } elseif ($user_today_count > 0 && $user_today_count < $this->user_day_max)
            {
                if ($user_today[0]['create_time'] + $this->time_interval > $time)
                {
                    return show(config('code.error'), '距上次领奖不到' . ceil((($time - $user_today[0]['create_time']) / 3600)) . '小时，请稍后再来领取！');
                }
                $user_surplus_times = $this->user_day_max - $user_today_count;
            } else
            {
                $user_surplus_times = $this->user_day_max;
            }
        }
        // 总抽奖次数+1
        $total_count++;
        // 所有奖项
        $all_prize = $LuckyPlanet->getAllPrize();
        // 获取所有奖项提示语
        $all_prize_tips = $LuckyPlanet->getAllPrizeTips();
        // 获取今日中奖详情
        $win_today = $LuckyPlanet->getWinToday();
        // 获取今日中奖次数
        $win_today_count = count($win_today);

        // status  0未中奖   1未提问   2待回答   3已回复   4已过期  5已兑换
        $data = ['uid' => $uid, 'create_time' => $time];

        $temp = [];
        // 随机数
//        $random = rand(1, $this->rand_max);
        $random = rand(7, $this->rand_max);

        if ($this->must_win > 0 && $total_count > 0 && $total_count % $this->must_win == 0)
        {
//            $random = rand(2, 6);
        }

//        if ($random > 1 && $random <= 6 && $win_today_count > 0)
//        {
//            // 当有区间必中时，那么那区间内只能中一个
//            $can_win = ceil($total_count / $this->must_win);
//            // 可中奖状态
//            if ($win_today_count < 5 && $this->must_win > 0 && $can_win > $win_today_count)
//            {
//                // 过滤已中奖选项
//                $all = [2 => '0002', 3 => '0003', 4 => '0004', 5 => '0005', 6 => '0006'];
//                $prize_text = [2 => '幸运水星', 3 => '幸运金星', 4 => '幸运火星', 5 => '幸运木星', 6 => '幸运土星'];
//
//                foreach ($win_today as $i => $wt) foreach ($prize_text as $j => $a) if ($wt['prize'] == $a) unset($all[$j]);
//
//                $surplus = array_keys($all);
//
//                $random = $surplus[rand(0, count($surplus) - 1)];
//            } else
//            {
//                // 今日奖励已无
//                $random = rand(7, $this->rand_max);
//            }
//        }
        // 完全随机
        // 幸运水星
        if ($random === 2)
        {
            $planet_num = '0002';
            $status = 1;
            // 幸运金星
        } elseif ($random === 3)
        {
            $planet_num = '0003';
            $status = 1;
            // 幸运火星
        } elseif ($random === 4)
        {
            $planet_num = '0004';
            $status = 1;
            // 幸运木星
        } elseif ($random === 5)
        {
            $planet_num = '0005';
            $status = 1;
            // 幸运土星
        } elseif ($random === 6)
        {
            $planet_num = '0006';
            $status = 1;
            // 12星座木星
        } elseif ($random >= $this->rand_max - 12)
        {
            $sign = sprintf('%02d', rand(1, 12));
            $planet_num = $sign . '05';
            $status = 0;
            // 普通星
        } else
        {
            $sign = sprintf('%02d', rand(1, 12));
            $planets = ['02', '03', '04', '06'];
            $planet_num = $sign . $planets[rand(0, 3)];
            $status = 0;
        }
        $prize = $all_prize[$planet_num]['prize'];
        $temp['status'] = $data['status'] = $status;
        $data['planet_num'] = $planet_num;
        $data['prize'] = $prize;
        $tip = $all_prize_tips[$planet_num][rand(0, count($all_prize_tips[$planet_num]) - 1)];
        $data['tipsid'] = $tip['id'];
        $data['type'] = 1;

        if ($status == 1) $temp['tip'] = $tip['text'];
        else $temp['tip'] = '你领到一颗' . $prize . ',' . $tip['text'];
        // 添加并更新缓存
        $temp['pid'] = $LuckyPlanet->addLuckyPlanet($data);
        $temp['get_time'] = $time;
        $temp['times'] = $user_surplus_times - 1;
        // 总抽奖次数 更新缓存
        Cache::set('lucky_planet_count_' . $date, $total_count, 86400);
        // 移除所有的幸运星ids
        Cache::rm($LuckyPlanet::REDIS_KEY_IDS . $uid);
        // 移除用户所有的提问回答ids
        Cache::rm(LuckyQuestionAnswer::REDIS_KEY_IDS . $uid);
        Cache::rm($LuckyPlanet::REDIS_KEY_DETAIL . $temp['pid']);
        // VIP每日幸运星任务 完成
        (new ZlUserVip())->updateStarNum($uid, 10);

        return show(config('code.success'), '领取成功', $temp);
    }

    /**
     * 去提问
     */
    public function push_question()
    {
        $pid = input('pid/d', 0);// 中奖id

        $content = trim(htmlspecialchars(input('text/s', '')));

        if (mb_strlen($content, 'utf8') > 100 || mb_strlen($content, 'utf8') < 5)
        {
            SensorsData::track($this->user['id'], true, 'LuckyPlanetAwardQuestion', [
                'is_success' => false,
                'failed_reson' => '提问字数不在5~100字内',
                'question' => $content,
            ]);
            return show(config('code.error'), '提问字数5~100字内');
        }
        if (!$pid)
        {
            SensorsData::track($this->user['id'], true, 'LuckyPlanetAwardQuestion', [
                'is_success' => false,
                'failed_reson' => '幸运星错误',
                'question' => $content,
            ]);
            return show(config('code.error'), '幸运星错误');
        }

        $uid = $this->user['id'];

        $LuckyPlanetModel = new LuckyPlanet();
        $LuckyQuestionAnswerModel = new LuckyQuestionAnswer();

        try
        {
            $my_prize = $LuckyPlanetModel
                ->where("uid=$uid and id=$pid and status=1")
                ->findOrFail();

            $time = $this->request->time();

            if ($my_prize['create_time'] + 86400 < $time)
            {
                $LuckyPlanetModel->where(['id' => $pid])->update(['status' => 4]);
            }

            $insert_data = [
                'lid' => $pid,
                'uid' => $uid,
                'question' => $content,
                'create_time' => $time,
                'status' => 0// 0 待回答  1已回答
            ];

            $LuckyQuestionAnswerModel->insert($insert_data);

            $LuckyPlanetModel->where(['id' => $pid])->update(['status' => 2]);
            // 今日日期
            $date = date('Ymd', $time);
            // 更新今日中奖缓存
            Cache::rm($LuckyPlanetModel::WIN_TODAY . $date);
            //删除幸运星详情pid
            Cache::rm($LuckyPlanetModel::REDIS_KEY_DETAIL . $pid);
            //删除用户所有的提问ids
            Cache::rm($LuckyQuestionAnswerModel::REDIS_KEY_IDS . $uid);
        }
        catch (\Exception $e)
        {
            \think\Log::write('幸运星提问失败：[uid:' . $uid . ',pid:' . $pid . ',content:' . $content . ']' . PHP_EOL . $e->getMessage(), 'error', true);
            SensorsData::track($this->user['id'], true, 'LuckyPlanetAwardQuestion', [
                'is_success' => false,
                'failed_reson' => $e->getMessage(),
                'question' => $content,
            ]);

            return show(config('code.error'), '请稍后重试');
        }

        SensorsData::track($this->user['id'], true, 'LuckyPlanetAwardQuestion', [
            'is_success' => true,
            'failed_reson' => '',
            'question' => $content,
        ]);

        return show(config('code.success'), '提问成功');
    }

    /**
     * 二维数组打乱顺序
     * @param $list
     * @return array
     */
    public function shuffle_assoc($list)
    {
        if (!is_array($list)) return $list;

        $keys = array_keys($list);

        shuffle($keys);

        $random = array();

        foreach ($keys as $key)
            $random[$key] = $list[$key];// 只打乱第一层key
//        $random[$key] = $this->shuffle_assoc($list[$key]);// 第二层key打乱
        return array_values($random);
    }
}
